document.getElementById('compare').addEventListener('click', async () => {
    const file1 = document.getElementById('file1').files[0];
    const file2 = document.getElementById('file2').files[0];

    if (!file1 || !file2) {
        alert('请上传两个Excel文件');
        return;
    }

    const resultDiv = document.getElementById('result');
    resultDiv.innerHTML = '<p>正在比较文件，请稍候...</p>';

    try {
        const data1 = await readExcel(file1);
        const data2 = await readExcel(file2);
        const differences = compareExcelData(data1, data2);

        if (differences.length === 0) {
            resultDiv.innerHTML = '<p>文件内容完全相同</p>';
        } else {
            let report = '<h2>差异报告</h2>';
            differences.forEach(diff => {
                report += `<p>${diff}</p>`;
            });
            resultDiv.innerHTML = report;
        }
    } catch (error) {
        resultDiv.innerHTML = `<p>比较过程中出错: ${error.message}</p>`;
    }
});

/**
 * 读取Excel文件内容并转换为JSON格式
 * @param {File} file - 上传的Excel文件
 * @param {string} [sheetName] - 可选参数，指定Sheet名称
 * @returns {Promise<Array>} - 返回解析后的JSON数据
 */
async function readExcel(file, sheetName) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = (e) => {
            try {
                const data = new Uint8Array(e.target.result);
                const workbook = XLSX.read(data, { type: 'array' });
                const sheet = sheetName ? workbook.Sheets[sheetName] : workbook.Sheets[workbook.SheetNames[0]];
                const jsonData = XLSX.utils.sheet_to_json(sheet);
                resolve(jsonData);
            } catch (error) {
                reject(error);
            }
        };
        reader.onerror = () => {
            reject(new Error('读取文件失败'));
        };
        reader.readAsArrayBuffer(file);
    });
}

/**
 * 比较两个Excel数据集的差异
 * @param {Array} data1 - 第一个文件的数据
 * @param {Array} data2 - 第二个文件的数据
 * @param {Array} [columnsToCompare] - 可选参数，指定需要比较的列
 * @returns {Array} - 返回差异报告
 */
function compareExcelData(data1, data2, columnsToCompare) {
    const differences = [];

    if (data1.length !== data2.length) {
        differences.push(`行数不同: 文件1有 ${data1.length} 行，文件2有 ${data2.length} 行`);
    }

    const maxRows = Math.min(data1.length, data2.length);
    for (let i = 0; i < maxRows; i++) {
        const row1 = data1[i];
        const row2 = data2[i];

        const keys = columnsToCompare || new Set([...Object.keys(row1), ...Object.keys(row2)]);
        for (const key of keys) {
            if (row1[key] !== row2[key]) {
                differences.push(`行 ${i + 1}, 列 "${key}": 文件1为 "${row1[key]}", 文件2为 "${row2[key]}"`);
            }
        }
    }

    return differences;
}